package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImppl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品
     * @param dishdto
     * @return
     */

    // 事务注解：确保dish和dish_flavor要么都成功，要么都回滚
    @Transactional
    public void addDish(DishDTO dishdto){
        //把三个表剥离
        Dish dish = Dish.builder()
                .name(dishdto.getName())
                .categoryId(dishdto.getCategoryId())
                .price(dishdto.getPrice())
                .image(dishdto.getImage())
                .description(dishdto.getDescription())
                .status(dishdto.getStatus())
                .build();

        // 处理dish表：插入后自动回填id
        dishMapper.insert(dish);
        Long dishId = dish.getId(); // 此时dishId就是新插入的dish的id

        List<DishFlavor> flavors = dishdto.getFlavors();

        if(flavors != null && !flavors.isEmpty()){
            flavors.forEach(flavor -> flavor.setDishId(dishId)); // 绑定外键

            //处理表dish_flavor    和  dish  多对一   在 “多” 的表中添加外键，关联 “一” 的表的 id
            dishFlavorMapper.insert(flavors);
        }

        //不用处理表category   因为 category 和  dish  一对多   在 “多” 的表中添加外键，关联 “一” 的表的 id
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO){
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());

        Page<DishVO> page = dishMapper.page(dishPageQueryDTO);

        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 根据ID查菜品
     * @param id
     * @return
     */
    @Transactional
    @Override
    public DishVO getById(Long id){
        Dish dish = dishMapper.getById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);

        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);

        dishVO.setFlavors(flavors);

        return dishVO;
    }

    /**
     * 修改菜品
     * @param dishdto
     * @return
     */
    @Transactional
    @Override
    public void updateDish(DishDTO dishdto){
        Dish dish = Dish.builder()
                .id(dishdto.getId())
                .name(dishdto.getName())
                .categoryId(dishdto.getCategoryId())
                .price(dishdto.getPrice())
                .image(dishdto.getImage())
                .description(dishdto.getDescription())
                .build();

        dishMapper.update(dish);

        dishFlavorMapper.deleteByDishId(dishdto.getId());

        List<DishFlavor> flavors = dishdto.getFlavors();
        if(flavors != null && !flavors.isEmpty()){
            flavors.forEach(flavor -> flavor.setDishId(dish.getId()));
            dishFlavorMapper.insert(flavors);
        }

    }

    /**
     * 起售停售菜品
     * @param status
     * @param id
     * @return
     */
    public void updateStatus(Integer status, Long id){
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();

        dishMapper.update(dish);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @Transactional
    @Override
    public void deleteById(List<Long> ids){
        //判断当前菜品是否能够删除---是否存在起售中的菜品？？
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);//后绪步骤实现
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //当前菜品处于起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //判断当前菜品是否能够删除---是否被套餐关联了？？
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        for(Long id : ids){
            dishMapper.delete(id);
            dishFlavorMapper.deleteByDishId(id);
        }


    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> getByCategoryId(Long categoryId){
        List<Dish> dishs = dishMapper.getByCategoryId(categoryId);

        return dishs;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
